package com.bum.rss.site;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.InitializingBean;

import com.bum.rss.exp.om.RssEntry;
import com.bum.rss.site.cat.BoyvnCat;
import com.bum.rss.site.util.BaseParser;

public class BoyvnSite extends Site implements BoyvnCat, InitializingBean {
	Logger							log			= Logger.getLogger(getClass());

	final HashMap<String, String>	CAT_CODES	= new HashMap<String, String>();
	final List<RssEntry>			CATEGORIES	= new ArrayList<RssEntry>(CATS.length);

	final Map<String, String>		CAT_TO_CODE	= new HashMap<String, String>();

	@Override
	public void afterPropertiesSet() throws Exception {
		for (int n = CATS.length, i = 0; i < n; i++) {
			CAT_CODES.put(CATS[i][0], CATS[i][2]);
			CATEGORIES.add(new RssEntry(getCode() + URL_SEPARATOR + CATS[i][0], CATS[i][1]));

			CAT_TO_CODE.put(CATS[i][2], CATS[i][0]);
		}
	}

	@Override
	public List<RssEntry> listSiteCats(String user) {
		return CATEGORIES;
	}

	@Override
	public List<RssEntry> listCatEntrys(String cat, String user) {
		int page = 1;
		if (cat.indexOf(PAGE_SEPARATOR) > 0) {
			String[] parts = StringUtils.split(cat, PAGE_SEPARATOR);
			page = NumberUtils.toInt(parts[1], 1);

			cat = parts[0];
		}
		int offset = (page - 1) * 8;

		if ("0".equals(cat)) {
			return listHomepage();
		}

		String catSrc = CAT_CODES.get(cat);
		if (catSrc == null) {
			return null;
		}
		String url = "http://www.boyvn.com/home/content/blogcategory/" + catSrc + "/8/" + offset + "/";
		try {
			url = URLEncoder.encode(url, "utf-8");
		} catch (UnsupportedEncodingException e) {
		}
		url = "http://bum-fetch.appspot.com/fetch?url=" + url;

		String html = BaseParser.loadHtml(url);
		html = html.replace("\"", "'").replace("“", "\"").replace("”", "\"");
		html = BaseParser.parseContent(html, "<table class='blog' cellpadding='0' cellspacing='0'>",
				"<span class='article_seperator'> </span> </td></tr></table>");

		if (StringUtils.isBlank(html)) {
			return null;
		}

		// str = str.replaceAll("(?<=<p>).*?(?=</p>)", "replacement");
//		html = html.replaceAll("(?<=<!--\\[if)(.*?)(?=<!\\[endif\\])", "");
		html = html.replaceAll("<!--\\[if (.*?)(?=<!\\[endif\\])", "");

		List<RssEntry> entries = new LinkedList<RssEntry>();

		String[] items = html.split("<td class='contentheading' width='100%'>");
		for (int i = 1; i < items.length; i++) {
			String item = items[i];

			String link = BaseParser.parseContent(item, "<a href='", "'");
			link = getRssLink(link, cat);

			String title = BaseParser.parseContent(item, "class='contentpagetitle'> ", "</a> </td>");

			item = BaseParser.parseContent(item, "<td valign='top' colspan='2'>", "</div>");
			String intro = BaseParser.parseContent(item, "<div align='justify'>", null);
			intro = BaseParser.removeHtmlTag(intro);

			String imgSrc = BaseParser.parseContent(item, "<img src='", "'");

			RssEntry entry = new RssEntry();
			entry.setTitle(title);
			entry.setUrl(link);
			entry.setIntro(intro);
			entry.setThumb(imgSrc);

			entries.add(entry);
		}

		if (entries.size() >= 8) {
			entries.add(new RssEntry(getCode() + URL_SEPARATOR + cat + PAGE_SEPARATOR + (page + 1), NEXT_PAGE_TITLE));
		}
		if (page > 1) {
			entries.add(0, new RssEntry(getCode() + URL_SEPARATOR + cat + PAGE_SEPARATOR + (page - 1), PREV_PAGE_TITLE));
		}

		return entries;
	}

	private List<RssEntry> listHomepage() {
		String url = "http://www.boyvn.com/home/";
		try {
			url = URLEncoder.encode(url, "utf-8");
		} catch (UnsupportedEncodingException e) {
		}
		url = "http://bum-fetch.appspot.com/fetch?url=" + url;

		String html = BaseParser.loadHtml(url);
		html = html.replace("\"", "'").replace("“", "\"").replace("”", "\"");

		html = BaseParser.parseContent(html, "<span class='article_seperator'>", "<!-- BEGIN: LEFT COLUMN -->");
		if (StringUtils.isBlank(html)) {
			return null;
		}

		html = html.replaceAll("<!--\\[if (.*?)(?=<!\\[endif\\])", "");
		html = html.replace("color: #999999", "color: gray");

		List<RssEntry> entries = new LinkedList<RssEntry>();

		String[] parts = html.split("<div class='ja-newsblock clearfix'>");
		for (int i = 1; i < parts.length - 1; i++) {
			String part = parts[i];

			String cat = BaseParser.parseContent(part, "<a href='", "'");
			String catLink = getRssLink(cat);
			String catName = BaseParser.parseContent(part, "<span>", "</span>");
			entries.add(new RssEntry(catLink, catName));

			cat = BaseParser.parseContent(catLink, "/", null);

			String content = BaseParser.parseContent(part, "<div class='ja-newscontent'>", "<ul class='ja-newslinks'>");
			String img = BaseParser.parseContent(content, "<img src='", "'");
			String title = BaseParser.parseContent(content, "alt='", "' title=").trim();
			String link = BaseParser.parseContent(content, "<a href='", "'");
			link = getRssLink(link, cat);

			content = BaseParser.cleanAttribute(content);
			content = BaseParser.parseContent(content, "<span>", "</span></div>");
			content = BaseParser.removeHtmlTag(content);

			RssEntry entry = new RssEntry(link, title);
			entry.setThumb(img);
			entry.setIntro(content);
			entries.add(entry);

			part = BaseParser.parseContent(part, "<ul class='ja-newslinks'> <li>", "</ul>");
			for (String line : StringUtils.splitByWholeSeparator(part, "<li>")) {
				String href = BaseParser.parseContent(line, "href='", "'");
				href = getRssLink(href, cat);

				String tit = BaseParser.parseContent(line, "'>", "</a>").trim();
				if (StringUtils.isNotBlank(href) && StringUtils.isNotBlank(tit)) {
					entries.add(new RssEntry(href, tit));
				}
			}
		}

		return entries;
	}

	@Override
	public String getRssLink(String httpLink) {
		return getRssLink(httpLink, "m");
	}

	// http://www.boyvn.com/home/content/view/11799/28/ => rss://boyvn/m/11799
	protected String getRssLink(String httpLink, String catId) {
		if (StringUtils.isBlank(httpLink)) {
			return null;
		}

		String id = BaseParser.parseContent(httpLink, "content/view/", "/");
		if (StringUtils.isBlank(id)) {
			id = BaseParser.parseContent(httpLink, "blogcategory/", null);
			if (StringUtils.isNotBlank(id)) {
				id = id.substring(id.indexOf("/") + 1, id.length() - 1);
				id = CAT_TO_CODE.get(id);
				if (StringUtils.isNotBlank(id)) {
					return getCode() + URL_SEPARATOR + id;
				}
			}
			return null;
		}

		return getCode() + URL_SEPARATOR + catId + URL_SEPARATOR + id;
	}

	static String[]	REP_FROM	= {
			"http://www.boyvn.com/home/images/stories/bao/", "http://antg.cand.com.vn/Images/reddot.gif",
			"http://www.boyvn.com/home/images/stories/2013/thang_11/4.gif"
								};
	static String[]	REP_TO		= {
			"", "", ""
								};

	@Override
	public RssEntry loadEntry(String path, String user) {
		String url = "http://www.boyvn.com/home/content/view/" + path + "/2/";
		try {
			url = URLEncoder.encode(url, "utf-8");
		} catch (UnsupportedEncodingException e) {
		}
		url = "http://bum-tool.appspot.com/fetch?url=" + url;

		String html = BaseParser.loadHtml(url);
		html = html.replace("\"", "`");
		String title = BaseParser.parseContent(html, "<td class=`contentheading` width=`100%`> ", " </td>");

		html = BaseParser.parseContent(html, "<table class=`contentpaneopen`>", "<div style='float:center; padding:6px ;'></div><br /> Lượt xem");
		if (StringUtils.isBlank(html)) {
			return null;
		}

		html = html.replaceAll("\\<!--\\[if .*?\\<!\\[endif\\]-->", "").replace("http://www.boyvn.com/home/images/stories/2013/thang_04/A-Quantam-C.png", "");
		String content = BaseParser.parseContent(html, "</td> </tr> <tr> <td valign=`top` colspan=`2`>", "<div class=\"clearthis10\"> </div>");

		if (title == null || content == null) {
			return null;
		}

		content = content.replace("http://ngoisao.vn/webskins/skins/news/images/ccrelated.png", "NONE");
		content = StringUtils.replaceEach(content, REP_FROM, REP_TO);
		content = BaseParser.retainTags(content, BaseParser.genRetainTags(new String[] {
				"a", "div", "p", "br", "img"
		}));
		content = content.replaceAll("\\<img src=`NONE`.*?\\<\\/a\\>", "");

		content = content.replace("`", "\"").replace("http://www.boyvn.com/home/images/stories/2014/thang_07/cn.png", "");

		RssEntry entry = new RssEntry();
		entry.setTitle(title.replace("`", "\""));
		entry.setContent(content);
		return entry;
	}

	public static void main(String[] args) throws Exception {
		BoyvnSite site = new BoyvnSite();
		site.afterPropertiesSet();

//		RssEntry detail = site.loadEntry("13086", null);
//		System.out.println(detail.getTitle());
//		System.out.println(detail.getContent());

		List<RssEntry> list = site.listCatEntrys("0", null);
		if (list != null) {
			for (RssEntry entry : list) {
				System.out.println(entry.getTitle());
			}
		}
	}
}
